import 'dart:io';

import 'package:cher_flare/common/models/ly_user_works_model.dart';
import 'package:cher_flare/modules/login/models/ly_login_info_manager.dart';
import 'package:cher_flare/utils/ly_data_manager.dart';
import 'package:cher_flare/utils/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:images_picker/images_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_manager/photo_manager.dart';
import '../../../utils/app_color.dart';

class LYAddWorksPage extends StatefulWidget {
  const LYAddWorksPage({super.key});

  @override
  State<LYAddWorksPage> createState() => _LYAddWorksPageState();
}

class _LYAddWorksPageState extends State<LYAddWorksPage> {
  final textController = TextEditingController();
  final titleController = TextEditingController();

  final List<Media> _selectedImage = [];

  void _postButtonDidClick() async {
    if (textController.text.isEmpty ||
        _selectedImage.isEmpty ||
        titleController.text.isEmpty) {
      EasyLoading.showToast('Images and selected labels are required！',
          duration: const Duration(seconds: 2));
      return;
    }
    EasyLoading.show();
    LYWorksModel model = LYWorksModel();
    final userInfo = LYLoginInfoManager.getInstance.loginModel?.userInfo;
    model.userId = userInfo?.userId;
    model.avatar = userInfo?.avatarUrl;
    model.nickname = userInfo?.nickname;
    model.isSave = true;
    model.description = textController.text;
    model.title = titleController.text;

    List<String> images = [];
    for (final media in _selectedImage) {
      File file = File(media.path);
      final imageData = file.readAsBytesSync();
      final path = await Utils.saveImageToFile(imageData);
      images.add(path);
    }
    model.cover = images.first;
    model.images = images;
    LYDataManager.share.addWorksData(model);
    Future.delayed(const Duration(seconds: 2)).then((value) {
      EasyLoading.dismiss();
      Get.back();
    });
  }

  void _pickerImage() async {
    final status = await Permission.photos.request();
    if (status == PermissionState.denied) {
      EasyLoading.showToast('You have not authorised this permission.');
      return;
    }

    List<Media>? result = await ImagesPicker.pick(
      count: 1,
      pickType: PickType.image,
    );
    if (result != null) {
      _selectedImage.addAll(result);
    }
    setState(() {});
  }

  void _takePhoto() async {
    final status = await Permission.camera.request();
    if (status == PermissionStatus.denied) {
      EasyLoading.showToast('You have not authorised this permission.');
      return;
    }
    List<Media>? result = await ImagesPicker.openCamera();
    if (result != null) {
      _selectedImage.addAll(result);
    }
    setState(() {});
  }

  void _addPictureButtonDidClick() {
    showModalBottomSheet(
      context: context,
      builder: (ctx) {
        return CupertinoActionSheet(
          actions: [
            InkWell(
              onTap: () {
                Navigator.of(context).pop();
                _takePhoto();
              },
              child: Container(
                height: 50,
                alignment: Alignment.center,
                child: const Text('Camera'),
              ),
            ),
            InkWell(
              onTap: () {
                Navigator.of(context).pop();
                _pickerImage();
              },
              child: Container(
                height: 50,
                alignment: Alignment.center,
                child: const Text('Photo Album'),
              ),
            ),
            InkWell(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Container(
                height: 50,
                alignment: Alignment.center,
                child: const Text('Cancel'),
              ),
            ),
          ],
        );
      },
      backgroundColor: Colors.transparent,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.colorD7FFDF,
        leading: InkWell(
          child: Image.asset(
            'assets/images/back_icon.png',
            width: 24,
            height: 24,
          ),
          onTap: () {
            Get.close(0);
          },
        ),
        elevation: 0,
        centerTitle: true,
        actions: [
          Container(
            width: 100,
            height: double.infinity,
            alignment: Alignment.center,
            child: InkWell(
              onTap: () => _postButtonDidClick(),
              child: Container(
                width: 50,
                height: 28,
                decoration: (_selectedImage.isNotEmpty &&
                        textController.text.isNotEmpty)
                    ? BoxDecoration(
                        gradient: const LinearGradient(colors: [
                          AppColors.colorCCFF78,
                          AppColors.color78FF85
                        ]),
                        border:
                            Border.all(color: AppColors.whiteColor, width: 1),
                        borderRadius: BorderRadius.circular(12),
                      )
                    : BoxDecoration(
                        color: AppColors.colorCCCCCC,
                        borderRadius: BorderRadius.circular(12),
                      ),
                alignment: Alignment.center,
                child: const Text(
                  'Post',
                  style: TextStyle(color: AppColors.whiteColor, fontSize: 12),
                ),
              ),
            ),
          ),
        ],
      ),
      backgroundColor: AppColors.whiteColor,
      body: _makeBody(),
    );
  }

  Widget _makeBody() {
    return Padding(
      padding: const EdgeInsets.only(top: 12, left: 20, right: 20),
      child: CustomScrollView(
        slivers: [
          _makeListView(),
          SliverToBoxAdapter(
            child: Container(
              alignment: Alignment.centerLeft,
              margin: const EdgeInsets.only(top: 12, bottom: 18),
              height: 60,
              decoration: const BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          color: AppColors.colorCCCCCC, width: 0.5))),
              child: TextField(
                textAlign: TextAlign.start,
                controller: titleController,
                keyboardType: TextInputType.multiline,
                style:
                    const TextStyle(fontSize: 17, color: AppColors.color333333),
                decoration: InputDecoration(
                  hintText: 'Enter your title：',
                  hintStyle: TextStyle(
                      fontSize: 20,
                      color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.5)),
                  enabledBorder: InputBorder.none,
                  disabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none,
                ),
                onChanged: (content) {
                  setState(() {});
                },
              ),
            ),
          ),
          SliverPadding(
            padding: const EdgeInsets.only(top: 24),
            sliver: SliverToBoxAdapter(
              child: Container(
                height: 231,
                width: double.infinity,
                alignment: Alignment.topLeft,
                padding: const EdgeInsets.only(top: 12, bottom: 12, right: 12),
                decoration: BoxDecoration(
                  color: AppColors.colorF6F8FA,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: TextField(
                  textAlign: TextAlign.start,
                  controller: textController,
                  maxLines: 100,
                  maxLength: 600,
                  keyboardType: TextInputType.multiline,
                  style: const TextStyle(
                      fontSize: 17, color: AppColors.color333333),
                  decoration: InputDecoration(
                    contentPadding: const EdgeInsets.only(left: 15),
                    hintText: "Start your creation...",
                    hintStyle: TextStyle(
                        fontSize: 12,
                        color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.5)),
                    enabledBorder: InputBorder.none,
                    disabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none,
                  ),
                  onChanged: (content) {
                    setState(() {});
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _makeListView() {
    return SliverGrid.builder(
      gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 110,
          mainAxisExtent: 128,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12),
      itemBuilder: (ctx, index) {
        if (index < _selectedImage.length) {
          final media = _selectedImage[index];
          return _makeImageItem(media);
        }
        return _makeAddItem();
      },
      itemCount: _selectedImage.length + 1,
    );
  }

  Widget _makeAddItem() {
    return InkWell(
      onTap: () {
        _addPictureButtonDidClick();
      },
      child: Container(
        width: 107,
        height: 128,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: AppColors.colorF6F8FA,
            borderRadius: BorderRadius.circular(12)),
        child: Image.asset('assets/images/record_camera.png'),
      ),
    );
  }

  Widget _makeImageItem(Media media) {
    return Container(
      width: 107,
      height: 128,
      decoration: BoxDecoration(
          color: AppColors.colorF6F8FA,
          borderRadius: BorderRadius.circular(12)),
      clipBehavior: Clip.hardEdge,
      child: Stack(
        fit: StackFit.expand,
        children: [
          Image.file(
            File.fromUri(Uri.file(media.path)),
            fit: BoxFit.cover,
          ),
          Positioned(
            top: 0,
            right: 0,
            child: InkWell(
              onTap: () {
                _selectedImage.remove(media);
                setState(() {});
              },
              child: Image.asset(
                'assets/images/delete_icon.png',
                width: 24,
                height: 24,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
